#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: 洪卫

import os
import sys
import serial
import time
import json
import timetool
import requests  # 引入requests库以获取淘宝时间
from sys import version_info  

def pythonVersion():
    return version_info.major

key1 = 1
key2 = 2

dtime = 0.040
tcount = 5
tdelay = 0.1

def get_taobao_time():
    try:
        response = requests.get("http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp")
        if response.status_code == 200:
            data = response.json()
            if data.get('data', {}).get('t'):
                timestamp = int(data['data']['t']) / 1000  # Convert to seconds
                return timestamp
    except Exception as e:
        print("Error while fetching time from Taobao:", str(e))
    return None

def getTime():
    global dtime, tdelay, tcount
    f = open('timer.txt', 'r')
    dat = f.read()
    f.close()
    configs = json.loads(dat)
    ttime = int(timetool.conventTimeFromStrConfig(configs['time']) * 1000)
    dtime = float(configs['tdtime'] / 1000.0)
    tcount = configs['tCount']
    tdelay = float(configs['delay'] / 1000.0)
    print('time1:%s' % (configs['time']))
    print(ttime, dtime, tcount)
    return ttime

def getTime2():
    global dtime2, tdelay2, tcount2
    f = open('timer2.txt', 'r')
    dat = f.read()
    f.close()
    configs = json.loads(dat)
    ttime = int(timetool.conventTimeFromStrConfig(configs['time']) * 1000)
    dtime2 = float(configs['tdtime'] / 1000.0)
    tcount2 = configs['tCount']
    tdelay2 = float(configs['delay'] / 1000.0)
    print('time:%s' % (configs['time']))
    print(ttime, dtime, tcount)
    return ttime

serialT = None

def readPort():
    global serialT
    time.sleep(0.003)
    n = serialT.inWaiting()
    if n > 0:
        pstr = serialT.read(n)
        if pythonVersion() == 2:
            print('setial read:%s' % (pstr))
        else:
            print('setial read:%s' % (str(pstr)))

def sendCmd(pcmd):
    global serialT
    back = None
    if pythonVersion() > 2:
        back = serialT.write(pcmd.encode())
    else:
        back = serialT.write(pcmd)
    serialT.flush()
    print('send cmd,:%s,isOk:%s' % (pcmd, str(back)))
    return back

type2Pins = {1: ['<0000>', '<FFFF>'], 2: ['<0000>', '<FFFF>']}

def delaylog(n):
    for i in range(n):
        print('after %ds well exit.' % (n - i))

def getDelay():
    lt = time.time()
    tbt = get_taobao_time()
    ltend = time.time()
    ldt = ltend - lt
    delayt = ldt/2.0
    print('ldt:',ldt)
    dt = tbt - lt - ldt
    print('lt:',lt)
    print('ltend:',ltend)
    print('tbt:',tbt)
    print('dt:',dt)
    return dt

def main():
    global serialT, tdelay, tcount
    f = open('config.txt', 'r')
    jstr = f.read()
    f.close()
    jdic = json.loads(jstr)
    t = serial.Serial(jdic['port'], jdic['btv'], timeout=0.5)
    serialT = t
    time.sleep(2)
    sendCmd('@')
    readPort()
    sendCmd('<FFFF>')

    ttime = getTime()
    tttime2 = getTime2()

    if not (key1 and key2 and ttime):
        print('init timer erro,and exit...')
        return

    isRuned = False
    isRuned2 = False
    dt = getDelay()
    isDelayAdk = False
    delaymtime = 0.002
    while True:
        time.sleep(delaymtime)  # 进行一个延时,防止占用CPU过高
        nt = time.time() + dt
        nowtime = int(nt * 1000)  # 使用淘宝时间替换time.time()获取的本地时间
        # print(nowtime)
        if ttime <= nowtime or tttime2 <= nowtime:
            if not isRuned and ttime <= nowtime:
                for i in range(tcount):
                    sendCmd(type2Pins[key1][0])
                    time.sleep(dtime)
                    sendCmd(type2Pins[key1][1])
                    time.sleep(tdelay)
                isRuned = True
            if not isRuned2 and tttime2 <= nowtime:
                for i in range(tcount2):
                    sendCmd(type2Pins[key2][0])
                    time.sleep(dtime2)
                    sendCmd(type2Pins[key2][1])
                    time.sleep(tdelay2)
                isRuned2 = True
        elif isRuned and isRuned2:  # 定时器已经运行
            print('run end ...')
            delaylog(10)
        elif not isDelayAdk:
            if ttime - nowtime <= 10000 or tttime2 - nowtime <= 10000:
                dt = getDelay()
                isDelayAdk = True
                delaymtime = 0.001
            
if __name__ == '__main__':
    main()
